package com.raos.example.memory.service;

import com.raos.example.memory.entity.ChatRoom;
import com.raos.example.memory.repository.ChatRoomRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 聊天室业务服务实现类
 *
 * @author raos
 * @date 2025-07-14 20:58
 */
@Service
public class ChatRoomServiceImpl implements ChatRoomService {

    @Autowired
    private ChatRoomRepository chatRoomRepository;

    @Override
    public List<ChatRoom> list(ChatRoom chatRoom) {
        return chatRoomRepository.findAll();
    }

    @Override
    public ChatRoom add(ChatRoom chatRoom) {
        Assert.isTrue(StringUtils.hasText(chatRoom.getRoomName()), "参数roomName不能为空");
        chatRoom.setRoomId(UUID.randomUUID().toString());
        chatRoom.setAddTime(LocalDateTime.now());
        return chatRoomRepository.save(chatRoom);
    }

    @Override
    public ChatRoom update(ChatRoom chatRoom) {
        Assert.isTrue(StringUtils.hasText(chatRoom.getRoomId()), "参数roomId不能为空");
        Assert.isTrue(StringUtils.hasText(chatRoom.getRoomName()), "参数roomName不能为空");
        ChatRoom query = new ChatRoom(chatRoom.getRoomId());
        Optional<ChatRoom> optional = chatRoomRepository.findOne(Example.of(query));
        if (optional.isPresent()) {
            ChatRoom room = optional.get();
            room.setRoomName(chatRoom.getRoomName());
            room.setVersion(room.getVersion() + 1);
            room.setUpdateTime(LocalDateTime.now());
            return chatRoomRepository.save(room);
        }
        throw new IllegalArgumentException("未找到对应的聊天室");
    }

    @Override
    public void delete(ChatRoom chatRoom) {
        Assert.isTrue(StringUtils.hasText(chatRoom.getRoomId()), "参数roomId不能为空");
        chatRoomRepository.delete(chatRoom);
    }

}
